<template>
	<view class="my-coupons-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">我的优惠券</view>
			<view class="navbar-right">
				<uni-icons type="refresh" size="20" @click="refreshCoupons"></uni-icons>
			</view>
		</view>
		
		<!-- 状态标签 -->
		<view class="status-tabs">
			<view class="tabs-container">
				<view 
					class="tab-item" 
					:class="{ active: currentStatus === status.key }"
					v-for="status in statusList" 
					:key="status.key"
					@click="switchStatus(status.key)"
				>
					<text class="tab-text">{{ status.name }}</text>
					<text class="tab-count" v-if="status.count > 0">({{ status.count }})</text>
				</view>
			</view>
		</view>
		
		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<uni-icons type="spinner-cycle" size="24" color="#007AFF"></uni-icons>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="currentCoupons.length === 0" class="empty-coupons">
				<uni-icons type="gift" size="48" color="#ccc"></uni-icons>
				<text class="empty-text">暂无{{ getCurrentStatusName() }}优惠券</text>
				<view class="empty-action" @click="goToCouponCenter">
					<text class="action-text">去领券中心看看</text>
				</view>
			</view>
			
			<view 
				v-else
				class="coupon-item" 
				v-for="(coupon, index) in currentCoupons" 
				:key="index"
				:class="{ 
					disabled: coupon.status === 'expired' || coupon.status === 'used',
					used: coupon.status === 'used',
					expired: coupon.status === 'expired'
				}"
				@click="handleCouponClick(coupon)"
			>
				<view class="coupon-left">
					<view class="coupon-amount">
						<text class="amount-symbol">¥</text>
						<text class="amount-value">{{ coupon.preferentialMoney || coupon.amount }}</text>
					</view>
					<view class="coupon-condition">满{{ coupon.triggerMoney || coupon.condition }}可用</view>
				</view>
				<view class="coupon-right">
					<view class="coupon-title">{{ coupon.name || coupon.title }}</view>
					<view class="coupon-desc">{{ coupon.type || coupon.description }}</view>
					<view class="coupon-validity">有效期至：{{ formatDate(coupon.validEnd) || formatDate(coupon.expireTime) || '暂无' }}</view>
					<view class="coupon-status">
						<view class="status-tag" :class="coupon.status">
							<text class="status-text">{{ getStatusText(coupon.status) }}</text>
						</view>
					</view>
				</view>
				<view class="coupon-tag" v-if="coupon.isHot">热</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore && currentCoupons.length > 0" class="load-more" @click="loadMoreCoupons">
			<text class="load-more-text">加载更多</text>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import { couponApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons
		},
		data() {
			return {
				userId: 1, // 默认用户ID，实际应该从登录状态获取
				currentStatus: 'unused',
				statusList: [
					{ key: 'unused', name: '待使用', count: 0 },
					{ key: 'used', name: '已使用', count: 0 },
					{ key: 'expired', name: '已过期', count: 0 }
				],
				allCoupons: [],
				hasMore: false,
				loading: false
			};
		},
		computed: {
			currentCoupons() {
				return this.allCoupons.filter(coupon => coupon.status === this.currentStatus);
			}
		},
		async mounted() {
			// 确保userId存在
			if (!this.userId) {
				this.userId = 1; // 设置默认值
				console.log('页面加载时设置默认用户ID:', this.userId);
			}
			await this.loadUserCoupons();
		},
		onShow() {
			// 页面显示时刷新数据
			this.loadUserCoupons();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 加载用户优惠券
			async loadUserCoupons() {
				try {
					this.loading = true;
					
					console.log('开始获取用户优惠券数据...');
					console.log('当前用户ID:', this.userId);
					
					// 确保userId存在
					if (!this.userId) {
						this.userId = 1; // 设置默认值
						console.log('设置默认用户ID:', this.userId);
					}
					
					// 使用新的API接口获取用户优惠券
					const result = await couponApi.getUserCoupons(this.userId);
					
					console.log('用户优惠券API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 检查API响应
					if (result && result.code === 200) {
						// 处理优惠券数据，添加过期检查和状态分类
						this.allCoupons = this.processCouponData(result.data);
						await this.updateStatusCounts();
						
						// 更新本地存储，确保状态同步
						this.updateLocalStorage(result.data);
						
						console.log('成功从后端获取用户优惠券数据，数量:', this.allCoupons.length);
					} else {
						console.log('后端数据获取失败，响应详情:', {
							hasResult: !!result,
							code: result?.code,
							hasData: !!result?.data,
							dataLength: result?.data?.length
						});
						this.allCoupons = [];
						uni.showToast({
							title: '暂无优惠券数据',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载用户优惠券失败:', error);
					this.allCoupons = [];
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 更新本地存储
			updateLocalStorage(userCouponsData) {
				const usedCoupons = [];
				const receivedCoupons = [];
				
				userCouponsData.forEach(userCoupon => {
					const couponId = userCoupon.couponId || userCoupon.c_id || userCoupon.id;
					if (couponId) {
						// 根据status字段判断状态
						const status = userCoupon.status || 0;
						if (status === 1) {
							usedCoupons.push(couponId);
						}
						receivedCoupons.push(couponId);
					}
				});
				
				uni.setStorageSync('usedCoupons', usedCoupons);
				uni.setStorageSync('receivedCoupons', receivedCoupons);
				console.log('本地存储已更新:', { usedCoupons, receivedCoupons });
			},
			
			// 处理优惠券数据，检查过期状态
			processCouponData(coupons) {
				if (!coupons || !Array.isArray(coupons)) return [];
				
				const now = new Date();
				return coupons.map(coupon => {
					// 支持多种状态字段名（后端可能使用不同的字段名）
					let status = coupon.status || coupon.useStatus || coupon.couponStatus || 'unused';
					
					// 标准化状态值
					if (status === '1' || status === 1 || status === 'used' || status === '已使用') {
						status = 'used';
					} else if (status === '0' || status === 0 || status === 'unused' || status === '未使用') {
						status = 'unused';
					} else if (status === '2' || status === 2 || status === 'expired' || status === '已过期') {
						status = 'expired';
					}
					
					// 如果优惠券有结束时间，检查是否过期
					if (coupon.expireTime) {
						try {
							const endDate = new Date(coupon.expireTime);
							if (endDate < now && status !== 'used') {
								// 只有未使用的优惠券才标记为过期
								status = 'expired';
							}
						} catch (error) {
							console.error('解析优惠券过期时间失败:', error);
						}
					}
					
					// 如果优惠券有validEnd字段，也检查
					if (coupon.validEnd && status !== 'used' && status !== 'expired') {
						try {
							const validEnd = new Date(coupon.validEnd);
							if (validEnd < now) {
								status = 'expired';
							}
						} catch (error) {
							console.error('解析优惠券有效期失败:', error);
						}
					}
					
					// 从本地存储检查使用状态（作为备用）
					const usedCoupons = uni.getStorageSync('usedCoupons') || [];
					if (usedCoupons.includes(coupon.couponId || coupon.id)) {
						status = 'used';
					}
					
					// 保持已使用状态，不要被过期检查覆盖
					if (status === 'used') {
						status = 'used';
					}
					
					console.log(`处理优惠券 ${coupon.id}: 原始状态=${coupon.status}, 处理后状态=${status}`);
					
					// 确保优惠券名称正确设置
					const couponName = coupon.couponName || coupon.name || coupon.title || '优惠券';
					
					return {
						...coupon,
						status: status,
						name: couponName, // 确保name字段存在
						title: couponName  // 确保title字段也存在
					};
				});
			},
			
			// 刷新优惠券
			async refreshCoupons() {
				await this.loadUserCoupons();
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				});
			},
			
			// 切换状态
			switchStatus(statusKey) {
				this.currentStatus = statusKey;
			},
			
			// 获取当前状态名称
			getCurrentStatusName() {
				const status = this.statusList.find(s => s.key === this.currentStatus);
				return status ? status.name : '';
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'unused': '待使用',
					'used': '已使用',
					'expired': '已过期'
				};
				return statusMap[status] || '';
			},
			
			// 处理优惠券点击
			async handleCouponClick(coupon) {
				// 检查优惠券状态，只有未使用的优惠券才能点击
				if (coupon.status === 'unused') {
					// 调试：打印优惠券信息
					console.log('点击的优惠券详情:', coupon);
					console.log('优惠券名称字段:', {
						name: coupon.name,
						title: coupon.title,
						couponName: coupon.couponName
					});
					
					const couponName = coupon.name || coupon.title || coupon.couponName || '优惠券';
					
					uni.showModal({
						title: '使用优惠券',
						content: `确定要使用"${couponName}"吗？`,
						success: async (res) => {
							if (res.confirm) {
								try {
									console.log('开始使用优惠券:', coupon);
									console.log('当前用户ID:', this.userId);
									
									// 确保userId存在
									if (!this.userId) {
										this.userId = 1; // 设置默认值
										console.log('设置默认用户ID:', this.userId);
									}
									
									// 使用coupon.couponId而不是coupon.id，因为coupon.id是用户优惠券记录ID
									const result = await couponApi.useCoupon(coupon.couponId || coupon.id, this.userId);
									
									console.log('使用优惠券API返回结果:', result);
									console.log('result.code:', result.code);
									console.log('result.data:', result.data);
									console.log('result.msg:', result.msg);
									
									// 根据你的request.js，API函数直接接收到{code, msg, data}格式
									if (result.code === 200) {
										uni.showToast({
											title: '使用成功',
											icon: 'success'
										});
										
										// 更新优惠券状态为已使用
										coupon.status = 'used';
										
										// 将使用状态同步到本地存储，确保状态持久化
										const usedCoupons = uni.getStorageSync('usedCoupons') || [];
										if (!usedCoupons.includes(coupon.couponId || coupon.id)) {
											usedCoupons.push(coupon.couponId || coupon.id);
											uni.setStorageSync('usedCoupons', usedCoupons);
										}
										
										// 刷新状态统计
										await this.updateStatusCounts();
										
										// 自动切换到已使用标签
										this.currentStatus = 'used';
									} else {
										uni.showToast({
											title: result.msg || '使用失败',
											icon: 'none'
										});
									}
								} catch (error) {
									console.error('使用优惠券失败:', error);
									uni.showToast({
										title: '使用失败，请重试',
										icon: 'none'
									});
								}
							}
						}
					});
				} else if (coupon.status === 'used') {
					uni.showToast({
						title: '此优惠券已使用',
						icon: 'none'
					});
				} else if (coupon.status === 'expired') {
					uni.showToast({
						title: '此优惠券已过期',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '此优惠券不可使用',
						icon: 'none'
					});
				}
			},
			
			// 跳转到领券中心
			goToCouponCenter() {
				uni.navigateTo({
					url: '/pages/Coupon/CouponCenter'
				});
			},
			
			// 更新状态计数
			async updateStatusCounts() {
				try {
					// 直接根据本地数据计算状态计数
					this.statusList.forEach(status => {
						status.count = this.allCoupons.filter(coupon => coupon.status === status.key).length;
					});
					
					console.log('状态计数更新:', this.statusList);
				} catch (error) {
					console.error('更新状态计数失败:', error);
				}
			},
			
			// 加载更多优惠券
			loadMoreCoupons() {
				uni.showToast({
					title: '没有更多优惠券了',
					icon: 'none'
				});
				this.hasMore = false;
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				try {
					const date = new Date(dateString);
					return date.toLocaleDateString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit'
					});
				} catch (error) {
					return dateString;
				}
			},

			// 显示调试信息
			showDebugInfo() {
				uni.showModal({
					title: '调试信息',
					content: JSON.stringify(this.allCoupons, null, 2),
					showCancel: false
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.my-coupons-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 40px;
			display: flex;
			justify-content: flex-end;
		}
	}
	
	// 状态标签
	.status-tabs {
		background-color: #ffffff;
		margin-bottom: 12px;
		
		.tabs-container {
			display: flex;
			padding: 0 16px;
			
			.tab-item {
				flex: 1;
				padding: 16px 8px;
				text-align: center;
				position: relative;
				
				.tab-text {
					font-size: 14px;
					color: #666666;
				}
				
				.tab-count {
					font-size: 12px;
					color: #999999;
					margin-left: 4px;
				}
				
				&.active {
					.tab-text {
						color: #007AFF;
						font-weight: bold;
					}
					
					.tab-count {
						color: #007AFF;
					}
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 20px;
						height: 2px;
						background-color: #007AFF;
						border-radius: 1px;
					}
				}
			}
		}
	}
	
	// 优惠券列表
	.coupon-list {
		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.loading-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
		}
		
		.empty-coupons {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.empty-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
			
			.empty-action {
				margin-top: 20px;
				
				.action-text {
					font-size: 14px;
					color: #007AFF;
					text-decoration: underline;
				}
			}
		}
		
		.coupon-item {
			display: flex;
			background-color: #ffffff;
			margin: 0 16px 12px 16px;
			border-radius: 8px;
			overflow: hidden;
			position: relative;
			
			&.disabled {
				opacity: 0.6;
			}
			
			&.used {
				opacity: 0.6;
				
				.coupon-left {
					background: linear-gradient(135deg, #999999, #cccccc);
				}
				
				.coupon-right {
					.coupon-title,
					.coupon-desc,
					.coupon-validity {
						color: #999999;
					}
				}
			}
			
			&.expired {
				opacity: 0.6;
				
				.coupon-left {
					background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
				}
				
				.coupon-right {
					.coupon-title,
					.coupon-desc,
					.coupon-validity {
						color: #999999;
					}
				}
			}
			
			.coupon-left {
				width: 120px;
				background: linear-gradient(135deg, #ff4757, #ff6b6b);
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 16px;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					right: -8px;
					top: 50%;
					transform: translateY(-50%);
					width: 16px;
					height: 16px;
					background-color: #f5f5f5;
					border-radius: 50%;
				}
				
				.coupon-amount {
					display: flex;
					align-items: baseline;
					margin-bottom: 8px;
					
					.amount-symbol {
						font-size: 16px;
						color: #ffffff;
						font-weight: bold;
					}
					
					.amount-value {
						font-size: 32px;
						color: #ffffff;
						font-weight: bold;
					}
				}
				
				.coupon-condition {
					font-size: 12px;
					color: #ffffff;
					opacity: 0.8;
				}
			}
			
			.coupon-right {
				flex: 1;
				padding: 16px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				
				.coupon-title {
					font-size: 16px;
					font-weight: bold;
					color: #333333;
					margin-bottom: 4px;
				}
				
				.coupon-desc {
					font-size: 12px;
					color: #666666;
					margin-bottom: 8px;
				}
				
				.coupon-validity {
					font-size: 12px;
					color: #999999;
					margin-bottom: 12px;
				}
				
				.coupon-status {
					.status-tag {
						display: inline-block;
						padding: 4px 8px;
						border-radius: 12px;
						font-size: 10px;
						
						&.unused {
							background-color: #e8f5e8;
							color: #52c41a;
						}
						
						&.used {
							background-color: #f0f0f0;
							color: #999999;
						}
						
						&.expired {
							background-color: #fff2f0;
							color: #ff4d4f;
						}
						
						.status-text {
							font-weight: bold;
						}
					}
				}
			}
			
			.coupon-tag {
				position: absolute;
				top: 8px;
				right: 8px;
				background-color: #ff4757;
				color: #ffffff;
				font-size: 10px;
				padding: 2px 6px;
				border-radius: 4px;
			}
		}
	}
	
	// 加载更多
	.load-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px;
		background-color: #ffffff;
		
		.load-more-text {
			font-size: 14px;
			color: #007AFF;
		}
	}
</style> 